package com.rcn.dal.hibernate;

import java.security.NoSuchAlgorithmException;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.rcn.core.security.SecurePassword;
import com.rcn.core.security.User;
import com.rcn.dal.interfaces.ILoginDAO;
import com.rcn.hibernate.HibernateUtil;


public class LoginDAO extends BaseDAO implements ILoginDAO{

	private static Logger log = LogManager.getLogger(LoginDAO.class.getName());
	
	public void updatePassword(String username, String password) throws NoSuchAlgorithmException{
		Session session = HibernateUtil.getSession();
		
		String hql = "FROM User u WHERE u.username = :username";
		Query query = session.createQuery(hql);
		query.setParameter("username",username);
		User user = null;
		try{
			user = (User) query.uniqueResult();
			try {
				byte[] newPassword = SecurePassword.hash(password);
				user.setPassword(newPassword);
				log.info("Updating password");
				update(user);
			} catch (NoSuchAlgorithmException e) {
				log.error("Error hashing pass");
				throw e;
			}
		}catch(HibernateException e){
			log.error("An error ocurred trying to get user "+username,e);
			throw e;
		}catch (ClassCastException e){
			log.error("Parse error trying to get user: "+username
					+". This error should never happen, but just in case.",e);
			throw e;
		}
	}
	
	public <T> String saveUserOrRole(T item)throws HibernateException{
        Session session = HibernateUtil.getSession();
        String generatedId = null;
        try
        {
            session.beginTransaction();
            generatedId = (String) session.save(item);
            session.getTransaction().commit();
        }catch(HibernateException e){
            session.getTransaction().rollback();
            throw new HibernateException("Ocurrio un problema al guardar. "+e.getMessage());
        }finally{
        	if(HibernateUtil.getSession()!=null)
                HibernateUtil.getSession().close();
        }
        return generatedId;
    }
}
